﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;


namespace ViVa.ActiveDirectory
{
    public class PermissionService
    {
        public static bool IsUserMemberOfbyUsername(string username, params string[] groupnames)
        {
            return IsUserMemberOfByADEntry(ADService.GetUserBySamAccountName(username), groupnames);
        }


        public static bool IsUserMemberOfByADEntry(ADEntry entry, params string[] groupnames)
        {
            var result = true;

            foreach (var groupname in groupnames)
            {
                if (!entry.MemberOf.Any(m => m.Contains(groupname)))
                {
                    result = false;
                }
            }
            
            return result;
        }

        public static void setPermission()
        {
            HttpContext.Current.Session["isHelpdesk"] = PermissionService.IsUserMemberOfbyUsername(userName(), "dl_portal_Helpdesk");
            HttpContext.Current.Session["isAdmin"] = PermissionService.IsUserMemberOfbyUsername(userName(), "dl_portal_Admin");

            if ((bool)HttpContext.Current.Session["isHelpdesk"] && (bool)HttpContext.Current.Session["isAdmin"])
            {
                HttpContext.Current.Session["isHelpdesk"] = false;
            }

            if (!(bool)HttpContext.Current.Session["isHelpdesk"] && !(bool)HttpContext.Current.Session["isAdmin"])
            {
                HttpContext.Current.Session["isGuest"] = true;
            }
                else { HttpContext.Current.Session["isGuest"] = false; };
        }

        public static string userName()
        {
            string strAccount = HttpContext.Current.User.Identity.Name.ToString();
            return strAccount.Split("\\".ToCharArray())[1];
        }
    }
}